// 充值收款成功页面
import React, {Component} from 'react';
import {StatusBar, Text, View, TouchableWithoutFeedback, TouchableOpacity, StyleSheet} from 'react-native';
import CXIcon from '../../../style/icon/CXIcon';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import storeActions from '../../../store/actions/store';
import {bindActionCreators} from 'redux';
import {Actions} from "react-native-router-flux";
import {connect} from "react-redux";
import {fen_to_yuan} from "../../../utils";
import Tips from "react-native-root-tips";
import {RNUSBPrinter} from "react-native-usb-printer-mi";
const Buffer = require('buffer').Buffer;

class balanceSuccessPage extends Component{
    constructor(props){
        super(props);
        this.state = {
            isPrint: false
        }
    }
    componentDidMount = async () => {
        const devices = await RNUSBPrinter.getUSBDeviceList();
        if (devices && devices.length) {
            let vendorId = '';
            let productId = '';
            let isPrint = false;
            let printedSelected = '';
            devices.forEach(item => {
                if (item.device_type == 7) {
                    vendorId = item.vendor_id;
                    productId = item.product_id;
                    isPrint = true;
                    this.setState({
                        isPrint: isPrint
                    })
                }
            });
            if (isPrint) {
                printedSelected = await RNUSBPrinter.connectPrinter(vendorId, productId);
            }
            this.setState(Object.assign({}, this.state, {
                printedSelected: printedSelected,
                devices: devices,
            }));
        }
        let {storeAction} = this.props;
        storeAction.getBalanceOrderDetail(this.props.order_no);
        this.setState({
            order_no: this.props.order_no
        })
    };
    // 打印单据
    printOrder() {
        if(this.state.printedSelected) {
            let {storeAction} = this.props;
            if (!this.state.order_no) {
                Tips.showFail('订单号错误');
                return
            }
            storeAction.getPrintInfo(this.state.order_no, res => {
                if (res.status) {
                    let arr = [];
                    Object.keys(res.data).forEach((v) => {
                        if (v !== 'logo' && v !== 'qrcode') {
                            res.data[v] = res.data[v].map((h) => {
                                return parseInt(h, 16)
                            })
                        }
                        arr.push(...res.data[v])
                    });
                    console.log('这个是之前的', arr);
                    var typedArray = new Buffer(arr);
                    console.log('获取到的', typedArray);
                    RNUSBPrinter.printTextCut(typedArray);
                }
            });
        }else{
            Tips.showFail('打印机未连接或者未授权');
        }
    }
    //查看订单性情
    _clickOrderDetail(){
        Actions.push('BalanceOrderPage',{
            order_no:this.props.order_no
        })
    }
    //跳到会员详情
    _clickVipDetail(){
        let{storeState} = this.props;
        Actions.push('MemberDetailPage',{
            type:'detail',
            user_id:storeState.orderBalanceDetail.order.user_id
        })

    }
    //渲染支付方式
    _renderPayments(payments){
        return payments.map((item,index) =>{
            return (
                <Text style={[index == payments.length -1 ? style.paymentsLast : '']} key={index}>
                    {item.channel_text}支付：￥{item.amount_yuan}
                </Text>
            )
        })
    }
    //渲染整个页面
    _renderPage(){
        let{storeState} = this.props;
        if(storeState.orderBalanceDetail && storeState.orderBalanceDetail.order&&storeState.orderBalanceDetail.order.order_no){
            return(
                <View style={style.page}>
                    <StatusBar hidden={true} />
                    <Text style={style.title}>
                        收款完成  ￥{storeState.orderBalanceDetail.order.pay_amount_yuan}
                    </Text>
                    <View style={{flexDirection: 'row', justifyContent: 'center'}}>
                        <Text style={style.miniTitle}> 会员充值：{storeState.orderBalanceDetail.order.balance_title}</Text>
                    </View>
                    <View style={style.infoBox}>
                        <View style={style.infoItem}>
                            <Text style={{flex: 1}}>
                                订单号：{storeState.orderBalanceDetail.order.order_no}
                            </Text>
                            <Text>
                                时间：{storeState.orderBalanceDetail.order.pay_time}
                            </Text>
                        </View>
                        <View style={style.infoItem}>
                            <View style={{flexDirection: 'row',flex: 1}}>
                                <Text style={{marginRight: 100}}>
                                    会员：{storeState.orderBalanceDetail.order.user.nick_name} {storeState.orderBalanceDetail.order.user.mobile}
                                </Text>
                                <Text>
                                    导购：{storeState.orderBalanceDetail.clerk.name}
                                </Text>
                            </View>
                            <TouchableWithoutFeedback>
                                <View style={style.noteBox}>
                                    <CXIcon name='beizhu' color='#909090' size={20}></CXIcon>
                                    <Text style={{marginLeft: 10}} numberOfLines={1}>备注: {storeState.orderBalanceDetail.order.note || ''}</Text>
                                </View>
                            </TouchableWithoutFeedback>

                        </View>
                        <View style={style.infoItem}>
                            <Text style={{flex: 1}}>
                                共1件
                            </Text>
                            <View style={style.itemLeft}>
                                <Text style={{marginRight: 50}}>
                                    商品总额：{storeState.orderBalanceDetail.order.amount_yuan}
                                </Text>

                                <Text>
                                    实收金额：<Text style={{color: mainBackgroundColor}}>￥{fen_to_yuan(storeState.orderBalanceDetail.actual)}</Text>
                                </Text>
                                <Text style={{paddingLeft: 50}}>
                                    找零金额：￥{fen_to_yuan(storeState.orderBalanceDetail.remaining)}
                                </Text>
                            </View>
                        </View>
                        <View style={style.infoItem}>
                            <TouchableWithoutFeedback onPress={() => this._clickOrderDetail()}>
                                <Text style={{flex: 1, color: '#4B8AF2'}}>
                                    查看充值订单详情
                                </Text>
                            </TouchableWithoutFeedback>
                            <View style={style.itemLeft}>
                                {this._renderPayments(storeState.orderBalanceDetail.payments)}
                            </View>
                        </View>
                    </View>

                    <View style={style.bottomBox}>
                        <TouchableWithoutFeedback onPress={() => this._clickVipDetail()}>
                            <View style={[style.btn, {marginRight: 80, backgroundColor: '#909090'}]}>
                                <Text style={style.btnText}>
                                    查看会员
                                </Text>
                            </View>
                        </TouchableWithoutFeedback>

                        <TouchableWithoutFeedback onPress={() => this.printOrder()}>
                            <View style={style.btn}>
                                <Text style={style.btnText}>
                                    打印收据
                                </Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
                </View>
            )
        }
    }

    render() {
        return (
            <View>
                {this._renderPage()}
            </View>
        )
    }
}

const style = StyleSheet.create({
    page: {
        backgroundColor: white,
        height: '100%',
        alignItems: 'center'
    },
    title: {
        fontSize: 38,
        color: '#F58B23',
        textAlign: 'center',
        marginTop: 110,
        marginBottom: 20
    },
    miniTitle: {
        color: mainBackgroundColor,
        fontSize: 16
    },
    infoBox: {
        width: 900,
        marginTop: 40,
    },
    infoItem: {
        flexDirection: 'row',
        // alignItems: 'center',
        padding: 20,
        borderTopWidth: 1,
        borderColor: '#DBDBDB'
    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    noteBox: {
        width: 175,
        flexDirection: 'row'
    },
    bottomBox: {
        position: 'absolute',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        left: 0,
        right: 0,
        bottom: 0,
        height: 90,
        borderTopWidth: 1,
        borderTopColor: '#DBDBDB'
    },
    btn: {
        width: 160,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 4,
        backgroundColor: mainBackgroundColor
    },
    btnText: {
        color: white
    }
});


export default connect(state =>({
    storeState: state.store
}),dispatch =>({
    storeAction: bindActionCreators(storeActions,dispatch)
}))(balanceSuccessPage);
